
package com.feib.ebilling.job.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;

import javax.annotation.Resource;

import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.feib.ebilling.job.dao.BankingFeedbackDao;
import com.feib.ebilling.job.dao.ThirdPartyFeedbackDao;


/**
 * @title (#)ThirdPartyFeedbackService.java<br>
 * @description <br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/12/10 create by Jimmy Liu<br>
 */
@Service("thirdPartyFeedbackService")
public class ThirdPartyFeedbackService extends BaseService  {
    
    public static Map<String, String> CHANEL_CODE = new HashMap<String, String>();
    static
    {
        CHANEL_CODE.put("7111111", "D");
        CHANEL_CODE.put("TFM", "E");
        CHANEL_CODE.put("HILIFE", "F");
        CHANEL_CODE.put("OKCVS", "G");
        CHANEL_CODE.put("POST", "H");
        /* 20120521  增加 ACH 通路銷帳  */
        CHANEL_CODE.put("ACH", "I");
    }

    @Resource(name="thirdPartyFeedbackDao")
    private ThirdPartyFeedbackDao thirdPartyFeedbackDao;
    
    @Resource(name="bankingFeedbackDao")
    private BankingFeedbackDao bankingFeedbackDao;
    
    @Resource(name="txManager")
    private PlatformTransactionManager transactionManager;

    /**
     * @param feedBackLog
     */
    @Transactional(readOnly = true)
    public Number addFeedbackLog(Map<String, Object> feedBackLog) {
        return thirdPartyFeedbackDao.insertFeedbackLog(feedBackLog);
    }

    /**
     * @param fileName
     */
    @Transactional(readOnly = true)
    public int removeFeedbackLog(String fileName) {
        return thirdPartyFeedbackDao.deleteFeedbackLog(fileName);
        
    }

    /**
     * @param fileName
     * @return
     */
    public boolean hasWriteoff(String fileName) {
        return this.bankingFeedbackDao.hasWriteoffLog(fileName);
    }

    /**
     * @param fileName
     */
    @Transactional(readOnly = true)
    public int deleteLogsByFileName(String fileName) {
        return this.bankingFeedbackDao.deleteLogsByFileName(fileName);
    }
    
    @Transactional(readOnly = false)
    public void writeoffByFile(String fileName)
    {
        // 建立交易的定義，每一次都是新的 Transaction
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        
        // 取得 DB Connection 
        Connection con = DataSourceUtils.getConnection(thirdPartyFeedbackDao.getDataSource());
        Statement stmt = null;
        try {
            stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            String sql = "select * from FEEDBACK_LOG where FBFILENAME = '" + fileName + "' and FEEDBACK_TYPE = 2 AND FBCODE = '0'";
            ResultSet rs = null;
            try {
                rs = stmt.executeQuery(sql);
                while (rs.next()){

                    TransactionStatus status = this.transactionManager.getTransaction(definition);                    
                    
                    /* 每一筆都要作，就算中間有 exception */
                    try {
                        processSingleWriteoffPayment(rs);
                        transactionManager.commit(status);
                    }
                    catch (Exception e) {
                        
                        logger.error("[錯誤]"+ e.getMessage(),  e);
                        
                        /* 異常，需例外處理 */
                        transactionManager.rollback(status);
                        status = null; // roll back 不需要再呼叫 commit
                        
                        // 更新WriteOffPayment 狀態
                        long uid = rs.getLong("UID");
                        
                        TransactionStatus status2 = this.transactionManager.getTransaction(definition);
                        try {
                            this.bankingFeedbackDao.updateWriteoffException(uid, e.getMessage());
                            transactionManager.commit(status2);
                        }
                        catch (Exception e2) {
                            logger.error("回寫銷帳狀態錯誤", e2);
                            transactionManager.rollback(status2);
                            status2 = null;
                        }
                    }
                } // end of while (rs.next())
                
            }
            finally {
                JdbcUtils.closeResultSet(rs);
            }
        }
        catch (Exception e) {
            JdbcUtils.closeStatement(stmt);
            stmt = null;
            DataSourceUtils.releaseConnection(con, thirdPartyFeedbackDao.getDataSource());
            con = null;
            throw new RuntimeException(e);
        }
        finally
        {
            JdbcUtils.closeStatement(stmt);
            stmt = null;
            DataSourceUtils.releaseConnection(con, thirdPartyFeedbackDao.getDataSource());
            con = null;
        }
    }

    /**
     * @param rs
     * @throws SQLException 
     * @throws ParseException 
     */
    private void processSingleWriteoffPayment(ResultSet rs) throws SQLException, ParseException {
        String channel = rs.getString("CHANNEL");
        /* 虛擬帳號 */
        String userno = rs.getString("USERNO");
        /* 20111014 查詢GROUP_TYPE不等於「4」.車貸策略聯盟的進行銷帳 */
        List<Map<String, Object>> groups = this.thirdPartyFeedbackDao.queryFeedbacklogByGroupType(userno);       
        if (0 == groups.size()) {
        	
         	 /* ACH後續銷帳流程與郵局相同  */
        	 if ("POST".equals(channel)){
        		 /* 20110615元智為學號、20110719變更為繳費帳號 */ 
              	 writeoffByPost(rs);
             }else if("ACH".equals(channel)){
            	 writeoffByAch(rs);
             }else{
             	 writeoffByStore(rs);
             }
        }else{
        	 logger.info( userno + "：車貸策略聯盟帳號暫不銷帳");
        }
    }

    /**
     * 郵局銷帳
     * @param rs
     * @throws ParseException 
     */
    private void writeoffByPost(ResultSet rs) throws SQLException, ParseException {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        long uid = rs.getLong("UID");
        String userno = rs.getString("USERNO");    //虛擬帳號
        String acct = rs.getString("ATMID");       //劃撥帳號
        String payerID = rs.getString("BARCDOE3"); //郵局會填學號
        String channel = rs.getString("CHANNEL");  //通路
        String aday = rs.getString("ADAY");        //交易日/顧客繳費日, 西元年月日
        Date fbTime = rs.getDate("FBTIME");        //銷帳時間(繳款核銷日), add by Jimmy Liu on 2011.04.07 因應報表需要 繳款交易日與繳款核銷日 修改
        
        long txamt = Long.parseLong(rs.getString("TXAMT")); //代收金額
                
        /* 劃撥帳號所屬帳單業者 */
        List<Map<String, Object>> groups = this.thirdPartyFeedbackDao.queryGroupForPostAcct(acct);
        if (0 == groups.size()) {
        	/* 未找到，需例外處理 */
            this.bankingFeedbackDao.updateWriteoffException(uid, acct + " 無此帳單業者之劃撥帳號");
            logger.info( acct + " 無此帳單業者之劃撥帳號");
        }else{
	        /* 郵局銷帳，劃撥帳號除元智外都用同一個 */
        	String group_pk = "";
        	for (int i = 0; i < groups.size(); i++) {
        		Map<String, Object> group = groups.get(i);
        		group_pk += (BigDecimal)group.get("GROUP_PK") + ",";
        	}
        	group_pk = group_pk.substring(0, group_pk.length() - 1);
	        List<Map<String, Object>> payments = this.thirdPartyFeedbackDao.queryUnWriteOffByPayerIDForPost(payerID, group_pk);
	        if (0 == payments.size())
	        {
	            /* 未找到，需例外處理 */
	            this.bankingFeedbackDao.updateWriteoffException(uid, payerID + " 無未銷帳資料");
	            logger.info( payerID + " 無未銷帳資料");
	        }
	        else if (1 == payments.size())
	        {
	            Map<String, Object> payment = payments.get(0);
	            /* 核對金額是否正確 */
	            long totalAmount = ((Number)payment.get("TOTAL_AMOUNT")).longValue(); // 繳費總金額
	            long totalLoanableAmount = 0;
	            if (payment.get("TOTAL_LOANABLE_AMOUNT") != null){
	                totalLoanableAmount = ((Number)payment.get("TOTAL_LOANABLE_AMOUNT")).longValue(); // 繳費總金額(可貸)
	            }
	            String paydue = dateFormat.format((Date)payment.get("PAY_DUE"));
	            
	            if (0 > paydue.compareTo(aday) &&  !channel.equals("POST") ) 
	            {
	                /* 顧客繳費日 超過 繳費期限，需例外處理 */
	                this.bankingFeedbackDao.updateWriteoffException(uid, "超過繳費期限：" + aday + " > " + paydue);
	                logger.info(userno + " 超過繳費期限：" + aday + " > " + paydue);
	            }
	            else if (txamt == totalAmount || txamt == totalLoanableAmount)
	            {
	                // Yes!
	                Map<String, Object> writeoffPayment = createEmptyWriteoffPayment();
	                /* 先新增到銷帳資料表*/
	                writeoffPayment.put("PAYMENT_PK", payment.get("PAYMENT_PK"));;
	                writeoffPayment.put("AMOUNT", txamt);//銷帳金額
	                writeoffPayment.put("CHANNEL", CHANEL_CODE.get(channel));
	                writeoffPayment.put("TX_DATE", dateFormat.parseObject(aday));//繳款交易日  ADAY, add by Jimmy Liu on 2011.04.07 因應報表需要 繳款交易日與繳款核銷日 修改
	                writeoffPayment.put("WRITE_OFF_DATE", fbTime);//銷帳時間(繳款核銷日), modify by Jimmy Liu on 2011.04.07 因應報表需要 繳款交易日與繳款核銷日 修改
	                writeoffPayment.put("WRITE_OFF_STATUS", new Integer(1)); //銷帳狀態- 正常
	                writeoffPayment.put("FEEDBACK_UID", new Long(uid));
	                
	                Number writeOffPaymentPk = this.bankingFeedbackDao.insertWriteOffPayment(writeoffPayment);
	                
	                /* 再更新 Payment */
	                payment.put("REAL_PAY_AMOUNT", txamt);
	                payment.put("WRITE_OFF_PAYMENT_PK", writeOffPaymentPk);
	                payment.put("UPDATE_BY", "ThirdPartyFeedBackbackJob");
	                payment.put("UPDATE_DATE", new Date());
	                this.bankingFeedbackDao.updatePaymentToWriteOffStatus(payment);
	                
	                this.bankingFeedbackDao.updateWriteoffDone(uid);
	                
	            }
	            else
	            {
	                /* 金額不符合，需例外處理 */
	                this.bankingFeedbackDao.updateWriteoffException(uid, "此金額不符合：" + txamt );
	                logger.info(userno + " 此金額不符合：" + txamt);
	            }
	        }
	        else
	        {
	            /* 只能有一筆未消帳資料，需例外處理  */ /* 源頭就有錯了，需要改轉入程式，或是修改規則 */
	            this.bankingFeedbackDao.updateWriteoffException(uid, "多筆未銷帳資料符合");
	            logger.info(userno + " 多筆未銷帳資料符合");
	        }
        }
    }

    /**
     * @param rs
     * @throws ParseException 
     */
    private void writeoffByStore(ResultSet rs) throws SQLException, ParseException {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        long uid = rs.getLong("UID");
        String userno = rs.getString("USERNO");     //虛擬帳號
        String barcode1 = rs.getString("BARCDOE1");
        String barcode2 = rs.getString("BARCDOE2");
        String barcode3 = rs.getString("BARCDOE3");
        long txamt = Long.parseLong(rs.getString("TXAMT"));
        String channel = rs.getString("CHANNEL"); // 通路
        String aday = rs.getString("ADAY"); //交易日/顧客繳費日, 西元年月日
        Date fbTime = rs.getDate("FBTIME"); //銷帳時間(繳款核銷日), add by Jimmy Liu on 2011.04.07 因應報表需要 繳款交易日與繳款核銷日 修改
        
        List<Map<String, Object>> payments = this.thirdPartyFeedbackDao.queryUnWriteOffByBarcode(barcode1, barcode2, barcode3);
        
        if (0 == payments.size())
        {
            /* 未找到，需例外處理 */
            this.bankingFeedbackDao.updateWriteoffException(uid, "無未銷帳資料");
            logger.info(userno + " 無未銷帳資料");
        }
        else if (1 == payments.size())
        {
            Map<String, Object> payment = payments.get(0);
            /* 核對金額是否正確 */
            long totalAmount = ((Number)payment.get("TOTAL_AMOUNT")).longValue(); // 繳費總金額
            long totalLoanableAmount = 0;
            if (payment.get("TOTAL_LOANABLE_AMOUNT") != null){
                totalLoanableAmount = ((Number)payment.get("TOTAL_LOANABLE_AMOUNT")).longValue(); // 繳費總金額(可貸)
            }
            String paydue = dateFormat.format((Date)payment.get("PAY_DUE"));
            
            if (0 >  paydue.compareTo(aday) && !channel.equals("POST")) 
            {
                /* 顧客繳費日 超過 繳費期限，需例外處理 */
                this.bankingFeedbackDao.updateWriteoffException(uid, "超過繳費期限：" + aday + " > " + paydue);
                logger.info(userno + "超過繳費期限：" + aday + " > " + paydue);
            }
            else if (txamt == totalAmount || txamt == totalLoanableAmount)
            {
                // Yes!
                Map<String, Object> writeoffPayment = createEmptyWriteoffPayment();
                /* 先新增到銷帳資料表*/
                writeoffPayment.put("PAYMENT_PK", payment.get("PAYMENT_PK"));
                writeoffPayment.put("AMOUNT", txamt);//銷帳金額
                writeoffPayment.put("CHANNEL", CHANEL_CODE.get(channel));
                writeoffPayment.put("TX_DATE", dateFormat.parseObject(aday));//繳款交易日  ADAY, add by Jimmy Liu on 2011.04.07 因應報表需要 繳款交易日與繳款核銷日 修改
                writeoffPayment.put("WRITE_OFF_DATE", fbTime);//銷帳時間(繳款核銷日), modify by Jimmy Liu on 2011.04.07 因應報表需要 繳款交易日與繳款核銷日 修改
                writeoffPayment.put("WRITE_OFF_STATUS", new Integer(1)); //銷帳狀態- 正常
                writeoffPayment.put("FEEDBACK_UID", new Long(uid));
                
                Number writeOffPaymentPk = this.bankingFeedbackDao.insertWriteOffPayment(writeoffPayment);
                
                /* 再更新 Payment */
                payment.put("REAL_PAY_AMOUNT", txamt);
                payment.put("WRITE_OFF_PAYMENT_PK", writeOffPaymentPk);
                payment.put("UPDATE_BY", "ThirdPartyFeedBackbackJob");
                payment.put("UPDATE_DATE", new Date());
                this.bankingFeedbackDao.updatePaymentToWriteOffStatus(payment);
                
                this.bankingFeedbackDao.updateWriteoffDone(uid);
                
            }
            else
            {
                /* 金額不符合，需例外處理 */
                this.bankingFeedbackDao.updateWriteoffException(uid, "此金額不符合" + txamt);
                logger.info(userno + " 此金額不符合" + txamt);
            }
        }
        else
        {
            /* 只能有一筆未消帳資料，需例外處理  */ /* 源頭就有錯了，需要改轉入程式，或是修改規則 */
            this.bankingFeedbackDao.updateWriteoffException(uid, "多筆未銷帳資料符合");
            logger.info(userno + " 多筆未銷帳資料符合");
        }
        
    }
    
    public Map<String, Object> createEmptyWriteoffPayment()
    {
        Map<String, Object> rd = new HashMap<String, Object>();
        
        rd.put("PAYMENT_PK", null);
        rd.put("CHANNEL", null);
        rd.put("AMOUNT", null);
        rd.put("TX_DATE", null); //add by Jimmy Liu on 2011.04.07 因應報表需要 繳款交易日與繳款核銷日 修改
        rd.put("WRITE_OFF_DATE", null);
        rd.put("WRITE_OFF_STATUS", null);
        rd.put("FEEDBACK_UID", null);
        
        
        rd.put("CREATED_BY", "ThirdPartyFeedBackbackJob");
        rd.put("CREATED_DATE", new Date());
        rd.put("UPDATE_BY", "ThirdPartyFeedBackbackJob");
        rd.put("UPDATE_DATE", new Date());
        
        return rd;
    }

    /**
     * @return
     */
    public List<String> loadCommissionCodes() {
        return this.thirdPartyFeedbackDao.loadCommissionCodes();
    }
    
    
    /**
     * 取得APP_GROUP Table內，新增的欄位APP_GROUP的ACH_EDIID欄位其中ACH_EDIID不為空白的資料。
     * @return ACH_EDIID
     * 
     */
    public List<Map<String, Object>>  loadAchEdiid() {
        return this.thirdPartyFeedbackDao.loadAchEdiid();
    }
    
    
    /**
     * 讀取ACH資料庫 DB名稱 
     * @param ACH_EDIID
     * @return
     */
    public Map<String, Object > getAchDBName(String ACH_EDIID) {
    	return this.thirdPartyFeedbackDao.getAchDBName(ACH_EDIID);
    }
    
    
    
    /**
     * 讀取ACH資料庫 Table名稱 
     * @param B304_ProfileID
     * @return
     */
    public Map<String, Object > getAchTableName(String B304_ProfileID) {
    	return this.thirdPartyFeedbackDao.getAchTableName(B304_ProfileID);
    }
    
    
    
  /**
   * 取得回饋資料
   * @param DBName
   * @param TableName
   * @param processSysDateROC
   * @return
   */
    public List<Map<String, Object>> getFeedbacklogFromACH(String DBName,String TableName,String processSysDateROC)  {    	
    	return this.thirdPartyFeedbackDao.getFeedbacklogFromACH(DBName, TableName, processSysDateROC);
    }
    
    
    /**
     * 取得帳單業者設定，虛擬帳號
     * @param groupPk
     * @return
     */
    public List<String> loadVirtualAccountNo(String groupPk) {
    	return this.thirdPartyFeedbackDao.loadVirtualAccountNo(groupPk);
    }
    
    

    /**
     * ACH銷帳
     * @param rs
     * @throws ParseException 
     */
    private void writeoffByAch(ResultSet rs) throws SQLException, ParseException {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        long uid = rs.getLong("UID");
        String userno = rs.getString("USERNO");    //虛擬帳號        
        String payerID = rs.getString("BARCDOE3"); //ACH通路的虛擬帳號為發動者專區 
        String channel = rs.getString("CHANNEL");  //通路
        String aday = rs.getString("ADAY");        //交易日/顧客繳費日, 西元年月日
        Date fbTime = rs.getDate("FBTIME");        //銷帳時間(繳款核銷日)
        
        long txamt = Long.parseLong(rs.getString("TXAMT")); //代收金額
                
        /* 因為沒有帳單業者劃撥帳號     改成直接查有AchEdiid*/
        List<Map<String, Object>> groups = this.thirdPartyFeedbackDao.loadAchEdiid();
        if (0 == groups.size()) {
        	/* 未找到，需例外處理 */
            this.bankingFeedbackDao.updateWriteoffException(uid, userno + "無帳單業者有設定AchEdiid");
            logger.info( " 無帳單業者有設定AchEdiid");
        }else{
	        
        	String group_pk = "";
        	for (int i = 0; i < groups.size(); i++) {
        		Map<String, Object> group = groups.get(i);
        		group_pk += (BigDecimal)group.get("GROUP_PK") + ",";
        	}
        	group_pk = group_pk.substring(0, group_pk.length() - 1);
	        List<Map<String, Object>> payments = this.thirdPartyFeedbackDao.queryUnWriteOffByPayerIDForPost(payerID, group_pk);
	        if (0 == payments.size())
	        {
	            /* 未找到，需例外處理 */
	            this.bankingFeedbackDao.updateWriteoffException(uid, payerID + " 無未銷帳資料");
	            logger.info( payerID + " 無未銷帳資料");
	        }
	        else if (1 == payments.size())
	        {
	            Map<String, Object> payment = payments.get(0);
	            /* 核對金額是否正確 */
	            long totalAmount = ((Number)payment.get("TOTAL_AMOUNT")).longValue(); // 繳費總金額
	            long totalLoanableAmount = 0;
	            if (payment.get("TOTAL_LOANABLE_AMOUNT") != null){
	                totalLoanableAmount = ((Number)payment.get("TOTAL_LOANABLE_AMOUNT")).longValue(); // 繳費總金額(可貸)
	            }
	            String paydue = dateFormat.format((Date)payment.get("PAY_DUE"));
	            
	            /*if (0 > paydue.compareTo(aday) &&  !channel.equals("ACH") ) {
	                // 顧客繳費日 超過 繳費期限，需例外處理 
	                this.bankingFeedbackDao.updateWriteoffException(uid, "超過繳費期限：" + aday + " > " + paydue);
	                logger.info(userno + " 超過繳費期限：" + aday + " > " + paydue);
	            }else*/ 
	            if (txamt == totalAmount || txamt == totalLoanableAmount){
	                // Yes!
	                Map<String, Object> writeoffPayment = createEmptyWriteoffPayment();
	                /* 先新增到銷帳資料表*/
	                writeoffPayment.put("PAYMENT_PK", payment.get("PAYMENT_PK"));;
	                writeoffPayment.put("AMOUNT", txamt);//銷帳金額
	                writeoffPayment.put("CHANNEL", CHANEL_CODE.get(channel));
	                writeoffPayment.put("TX_DATE", dateFormat.parseObject(aday));//繳款交易日  ADAY
	                writeoffPayment.put("WRITE_OFF_DATE", fbTime);//銷帳時間(繳款核銷日)
	                writeoffPayment.put("WRITE_OFF_STATUS", new Integer(1)); //銷帳狀態- 正常
	                writeoffPayment.put("FEEDBACK_UID", new Long(uid));
	                
	                Number writeOffPaymentPk = this.bankingFeedbackDao.insertWriteOffPayment(writeoffPayment);
	                
	                /* 再更新 Payment */
	                payment.put("REAL_PAY_AMOUNT", txamt);
	                payment.put("WRITE_OFF_PAYMENT_PK", writeOffPaymentPk);
	                payment.put("UPDATE_BY", "ThirdPartyFeedBackbackJob");
	                payment.put("UPDATE_DATE", new Date());
	                this.bankingFeedbackDao.updatePaymentToWriteOffStatus(payment);
	                
	                this.bankingFeedbackDao.updateWriteoffDone(uid);
	                
	            }else{
	                /* 金額不符合，需例外處理 */
	                this.bankingFeedbackDao.updateWriteoffException(uid, "此金額不符合：" + txamt );
	                logger.info(userno + " 此金額不符合：" + txamt);
	            }
	        }else{
	            /* 只能有一筆未消帳資料，需例外處理  */ /* 源頭就有錯了，需要改轉入程式，或是修改規則 */
	            this.bankingFeedbackDao.updateWriteoffException(uid, "多筆未銷帳資料符合");
	            logger.info(userno + " 多筆未銷帳資料符合");
	        }
        }
    }

    public List<Map<String, Object>> queryGroupForAchEdiid(String achEdiid) {
    	
    	return this.thirdPartyFeedbackDao.queryGroupForAchEdiid(achEdiid);
    } 
    
    public  String getHoliday(String processDate){
    	
    	return this.thirdPartyFeedbackDao.getHoliday(processDate);
   	
    }
    
}
